/*
 *  Copyright (C) 2010 Interactive Media Management
 * 
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 * 
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 * 
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package dk.i2m.converge.plugins.alertaction;

import dk.i2m.converge.core.plugin.WorkflowAction;
import dk.i2m.converge.core.Notification;
import dk.i2m.converge.core.content.NewsItem;
import dk.i2m.converge.core.content.NewsItemActor;
import dk.i2m.converge.core.plugin.PluginContext;
import dk.i2m.converge.core.security.UserAccount;
import dk.i2m.converge.core.workflow.WorkflowStepAction;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.antlr.stringtemplate.StringTemplate;
import org.antlr.stringtemplate.language.DefaultTemplateLexer;

/**
 * Workflow action for creating an alert.
 *
 * For the {@code message} property, the following variables are available:
 *
 * <ul>
 *     <li>initiator</li>
 *     <li>newsitem</li>
 * </ul>
 *
 * All variables must be enclosed in dollar signs, e.g. $action-initiator$.
 *
 * @author Allan Lykke Christensen
 */
@dk.i2m.converge.core.annotations.WorkflowAction
public class AlertAction extends WorkflowAction {

    public static final String MSG_VARIABLE_ACTION_INITIATOR = "action-initiator";

    public static final String MSG_VARIABLE_NEWS_ITEM_TITLE = "newsitem-title";

    public static final String MSG_VARIABLE_NEWS_ITEM_BRIEF = "newsitem-brief";

    public static final String MSG_VARIABLE_NEWS_ITEM_BRIEFING = "newsitem-briefing";

    public static final String MSG_VARIABLE_NEWS_ITEM_DEADLINE = "newsitem-deadline";

    public static final String RECIPIENT_USER = "recipient.user";

    public static final String RECIPIENT_ROLE = "recipient.role";

    public static final String MESSAGE = "message";

    private Map<String, String> availableProperties = null;

    private static final Logger logger = Logger.getLogger(AlertAction.class.getName());

    private ResourceBundle msgs = ResourceBundle.getBundle("dk.i2m.converge.plugins.alertaction.Messages");

    /**
     * Creates a new instance of {@link AlertAction}.
     */
    public AlertAction() {
    }

    @Override
    public void execute(PluginContext ctx, NewsItem item, WorkflowStepAction stepAction, UserAccount user) {
        Map<String, String> properties = stepAction.getPropertiesAsMap();

        if (!properties.containsKey(AlertAction.MESSAGE)) {
            logger.log(Level.WARNING, "{0} property missing from action properties", AlertAction.MESSAGE);
            return;
        }

        if (!properties.containsKey(AlertAction.RECIPIENT_USER) && !properties.containsKey(AlertAction.RECIPIENT_ROLE)) {
            logger.log(Level.WARNING, "{0} or {1} property missing from action properties", new Object[]{AlertAction.RECIPIENT_USER, AlertAction.RECIPIENT_ROLE});
            return;
        }

        boolean sendToUser = false;
        String sendToUserRole = "";
        boolean sendToRole = false;
        String sendToRoleRole = "";

        if (properties.containsKey(AlertAction.RECIPIENT_USER)) {
            sendToUser = true;
            sendToUserRole = properties.get(AlertAction.RECIPIENT_USER);
        }

        if (properties.containsKey(AlertAction.RECIPIENT_ROLE)) {
            sendToRole = true;
            sendToRoleRole = properties.get(AlertAction.RECIPIENT_ROLE);
        }

        StringTemplate template = new StringTemplate(properties.get(AlertAction.MESSAGE), DefaultTemplateLexer.class);
        template.setAttribute("newsitem", item);
        template.setAttribute("initiator", user);
        String notificationMessage = template.toString();

        List<UserAccount> usersToNotify = new ArrayList<UserAccount>();

        if (sendToUser) {
            for (NewsItemActor actor : item.getActors()) {
                if (actor.getRole().getName().equalsIgnoreCase(sendToUserRole)) {
                    usersToNotify.add(actor.getUser());
                }
            }
        }

        if (sendToRole) {
            usersToNotify.addAll(ctx.findUserAccountsByRole(sendToRoleRole));
        }

        for (UserAccount ua : usersToNotify) {
            Notification notification = new Notification();
            notification.setMessage(notificationMessage);
            notification.setAdded(Calendar.getInstance());
            notification.setRecipient(ua);
            ctx.createNotification(notification);
        }
    }

    @Override
    public Map<String, String> getAvailableProperties() {
        if (availableProperties == null) {
            availableProperties = new LinkedHashMap<String, String>();
            availableProperties.put("Recipient (user)", RECIPIENT_USER);
            availableProperties.put("Recipient (role)", RECIPIENT_ROLE);
            availableProperties.put("Message", MESSAGE);
        }
        return availableProperties;
    }

    @Override
    public String getName() {
        return msgs.getString("PLUGIN_NAME");
    }

    @Override
    public String getDescription() {
        return msgs.getString("PLUGIN_DESCRIPTION");
    }

    @Override
    public String getVendor() {
        return msgs.getString("PLUGIN_VENDOR");
    }

    @Override
    public Calendar getDate() {
        return Calendar.getInstance();
    }
}
